<template>
  <el-dialog :visible="modalVisible" :title="formData ? '编辑部门' : '新增部门'" @close="hide">
    <div style="width: 50%; margin-left: 25%">
      <el-form ref="orgEditRef" :model="form_data" label-width="100px" :rules="rules" >
        <el-form-item label="部门名称" prop="dept_name">
          <el-input v-model="form_data.dept_name" style="width:350px"/>
        </el-form-item>
        <el-form-item v-show="formData" label="唯一编码" prop="dept_id">
          <el-input v-model="form_data.dept_id" :disabled="!!formData" style="width:350px"/>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <el-select v-model="form_data.parent_id" placeholder="请选择"  style="width:350px">
            <el-option :value="currentOrg.id" :label="currentOrg.name" style="height: auto">
              <el-tree
                  ref="orgTreeRef"
                  default-expand-all
                  :expand-on-click-node="false"
                  :data="orgTreeData"
                  node-key="id"
                  highlight-current
                  :props="{children: 'children', label: 'name', disabled: disabledNode}"
                  @node-click="handleCheckChange"
              />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门正职" prop="leader_id">
          <el-select v-model="form_data.leader_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in peopleList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考勤员" prop="attendance_id">
          <el-select v-model="form_data.attendance_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in peopleList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分管领导" prop="assistant_id">
          <el-select v-model="form_data.assistant_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in peopleList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门等级" prop="level">
          <el-select v-model="form_data.level" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in levelList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="modalVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {deptList, deptEdit, deptAdd} from '@/utils/dept';
import {userListSelect} from "@/utils/user";

export default {
  name: 'EditDepartment',
  props: {
    formData: {
      type: Object,
      default: null
    }
  },
  data() {
    const validatePid = (rule, value, callback) => {
      if (this.form_data.parent_id !== '' && this.form_data.parent_id !== undefined) {
        callback()
      } else {
        callback(new Error('上级部门不能为空'));
      }
    };
    return {
      peopleList:[],
      levelList:[
        {
          id:3,
          name:'三级单元'
        },
        {
          id:4,
          name:'四级单元'
        },
        {
          id:5,
          name:'五级单元'
        },
        {
          id:6,
          name:'六级单元'
        }
      ],
      modalVisible: false,
      form_data: {
        // dept_name:'', //部门名称
        // assistant_id:'', //分管领导
        // attendance_id:'',//考勤员
        // leader_id:'', //部门正职
        // level:'', //几级单元
        // parent_id: '', //父级编号
        // dept_id: '',//修改部门信息的回显
      },
      orgTreeData: [],
      currentOrg: {},
      rules: {
        dept_name: [
          {
            required: true, message: '部门名称不能为空', trigger: 'blur'
          }
        ],
        parent_id: [
          {
            required: true, validator: validatePid
          }
        ],
        assistant_id: [
          {
            required: true, message: '请选择分管领导', trigger: 'blur'
          }
        ],
        attendance_id: [
          {
            required: true, message: '请选择考勤员', trigger: 'blur'
          }
        ],
        leader_id: [
          {
            required: true, message: '请选择部门正职', trigger: 'blur'
          }
        ],
        level: [
          {
            required: true, message: '请选择部门级别', trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    formData: {
      immediate: true,
      deep: true,
      handler(n, o) {
        if (n && n !== o) {
          this.form_data = JSON.parse(JSON.stringify(n))
        } else {
          this.form_data = {
          };
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init(){
      userListSelect({}).then(res=>{
        if(res.code === "1"){
          this.peopleList = res.data
        }
      })
    },
    disabledNode(data) {
      return data.disabled;
    },
    handleSubmit() {
      this.$refs['orgEditRef'].validate((res) => {
        if (res) {
          if(!this.formData){
            console.log('新增')
            const requestBody = {
              ...this.form_data
            };
            console.log('this.form_data',requestBody)
            deptAdd(requestBody).then(res => {
              if (res.code === "1") {
                this.$message.success(res.message);
                this.$emit('callback');
                this.hide();
              }else{
                this.$message.error(res.message)
              }
            });
          }else{
            console.log('编辑')
            delete this.form_data.assistant__name
            delete this.form_data.attendance__name
            delete this.form_data.leader__name
            delete this.form_data.parent_name
            delete this.form_data.nums
            delete this.form_data.status
            const requestBody = {
              ...this.form_data
            };
            console.log('this.form_data',requestBody)
            deptEdit(requestBody).then(res => {
              if (res.code === "1") {
                this.$message.success(res.message);
                this.$emit('callback');
                this.hide();
              }else{
                this.$message.error(res.message)
              }
            });
          }
        }
      });
    },
    handleCheckChange(data) {
      if (!data.disabled || !this.formData) {
        this.currentOrg = data;
        this.form_data.parent_id = data.id;
        // this.$refs['orgEditRef'].clearValidate();
        this.$refs['orgEditRef'].validateField('dept_id');
      } else {
        this.$message.warning('上级部门不可为自身');
      }
    },
    recursionGet(data, valueId) {
      let value = null;
      for (let index = 0; index < data.length; index += 1) {
        if (data[index].id === valueId) {
          value = data[index];
          break;
        }
        if (data[index].children instanceof Array && data[index].children.length > 0) {
          const text = this.recursionGet(data[index].children, valueId);
          if (text) {
            return text;
          }
        }
      }
      return value;
    },
    showDialog(){
      this.modalVisible = true;
      this.getOrgTree();
      // console.log('111',this.form_data)
      // console.log('222',this.formData)
    },
    hide() {
      this.currentOrg = {};
      this.$refs['orgEditRef'].resetFields();
      this.modalVisible = false;
      this.$emit('callback');
    },
    mapTree(data) {
      data.forEach(items => {
        if (items.id === this.formData.dept_id) {
          items.disabled = true
        } else {
          items.disabled = false
        }
        if (items.children) {
          this.mapTree(items.children)
        }
      });
    },
    getOrgTree() {
      deptList({}).then(res => {
        if (res.code === 1) {
          if (this.formData) {
            this.mapTree(res.data);
          }
          this.orgTreeData = [{
            id: 1,
            name: '淮南分公司',
            children: res.data,
            disabled: false
          }];
          if (this.form_data.parent_id !== '' && this.form_data.parent_id !== undefined && this.form_data.parent_id !== null) {
            this.currentOrg = this.recursionGet(this.orgTreeData, this.form_data.parent_id)
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
